import express from 'express';
import multer from 'multer';
import path from 'path';
import fs from 'fs';
import routerHandle from '../routerHandle/index.js';
const router=express.Router();
// 验证中间件
var upload = multer({
  storage: multer.diskStorage({
      //设置文件存储位置
      destination: function (req, file, cb) {
          let dir = "./img" 
          //设置图片存储位置
          // 上传文件路径
          
          //判断目录是否存在，没有则创建
          if (!fs.existsSync(dir)) {
              fs.mkdirSync(dir, {
                  recursive: true
              });
          }

          //dir就是上传文件存放的目录
          cb(null, dir);

      },
      filename: function (req, file, cb) {
          let fileName = req.body.userName +  path.extname(file.originalname);
          //fileName就是上传文件的文件名
          cb(null, fileName);
      }
  })
})
// 上传文章中间件
var uploadd = multer({
    storage: multer.diskStorage({
        //设置文件存储位置
        destination: function (req, file, cb) {
            let dir = "./context" 
            //设置图片存储位置
            // 上传文件路径
            
            //判断目录是否存在，没有则创建
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, {
                    recursive: true
                });
            }
  
            //dir就是上传文件存放的目录
            cb(null, dir);
  
        },
        
        filename: function (req, file, cb) {
            var userInfo=JSON.parse(req.body.userInfo);
            req.userInfo=userInfo;
            // 获取当前年月日时分秒
            let date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let hour = date.getHours();
            let minute = date.getMinutes();
            let second = date.getSeconds();
            req.time=year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + second;
            let fileName = userInfo.openid+"-"+year + "-" + month + "-" + day + "-" + hour + "-" + minute + "-" + second + path.extname(file.originalname);
            //fileName就是上传文件的文件名
            cb(null, fileName);
        }
    })
  })
router.post('/uploadInfo',upload.single("file"),routerHandle.uploadInfo)
router.get('/getMessage',routerHandle.getMessage)
router.post('/postMessage',uploadd.single("file"),routerHandle.postMessage)
router.get('/login',routerHandle.login)
router.get('/loginn',routerHandle.loginn)
export default router